package com.example.demo03_mvm.viewmodel;

import android.app.Application;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.demo03_mvm.R;
import com.example.demo03_mvm.adapter.GoodsAdapter;
import com.example.demo03_mvm.adapter.GoodsListAdapter;
import com.example.demo03_mvm.databinding.ActivityMainBinding;
import com.example.demo03_mvm.databinding.FragmentHomeBinding;
import com.example.demo03_mvm.databinding.FragmentTypeBinding;
import com.example.demo03_mvm.db.DBInstance;
import com.example.demo03_mvm.db.Goods;
import com.example.demo03_mvm.db.GoodsDao;
import com.example.demo03_mvm.model.GoodsEntity;
import com.example.demo03_mvm.model.GoodsTypeEntity;
import com.example.demo03_mvm.repos.GoodsTypeRepos;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

public class MainViewModel extends BaseViewModel {
    GoodsTypeRepos typeRepos = new GoodsTypeRepos();
    GoodsDao goodsDao;
    SearchView sv;
    public MainViewModel(@NonNull Application application) {
        super(application);
        goodsDao = DBInstance.getGoodsDataBase().getGoodsDao();
    }
    int page=1;
    GoodsListAdapter listAdapter;
    MutableLiveData<GoodsEntity> goodList;
    public MutableLiveData<GoodsTypeEntity> getTypes(){
        MutableLiveData<GoodsTypeEntity> types = typeRepos.getTypes();
        return types;
    }

    public void getGoods(int tid, LifecycleOwner owner, FragmentTypeBinding binding){
        GoodsAdapter goodsAdapter = new GoodsAdapter(R.layout.item_goods, new ArrayList<>());
        binding.rvGoods.setAdapter(goodsAdapter);
        binding.rvGoods.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));

        MutableLiveData<GoodsTypeEntity> goods = typeRepos.getGoods(tid);
        goodsAdapter.getData().clear();
        goods.observe(owner, new Observer<GoodsTypeEntity>() {
            @Override
            public void onChanged(GoodsTypeEntity goodsTypeEntity) {
                goodsAdapter.getData().addAll(goodsTypeEntity.getData());
                goodsAdapter.notifyDataSetChanged();

            }
        });


    }

    public void initAdapter(FragmentHomeBinding binding,LifecycleOwner owner){
        listAdapter = new GoodsListAdapter(R.layout.item_goodslist, new ArrayList<>());
        binding.rvGoodlist.setAdapter(listAdapter);
        binding.rvGoodlist.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        listAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                ARouter.getInstance().build("/app/DetailActivity").withInt("id",listAdapter.getData().get(position).getId()).navigation();
            }
        });

        binding.sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            //回车时执行的方法
            @Override
            public boolean onQueryTextSubmit(String query) {
                Log.i("===","onQueryTextSubmit:"+query);
                return true;
            }
            //文本改变时执行的方法
            @Override
            public boolean onQueryTextChange(String newText) {
                if(!newText.isEmpty()) {//内容不为空，根据输入内容做模糊搜索
                    ArrayList<GoodsEntity.DataBean> beans = new ArrayList<>();
                    for (GoodsEntity.DataBean bean : listAdapter.getData()) {
                        if (bean.getGoods_desc().contains(newText)) {
                            beans.add(bean);
                        }
                    }
                    listAdapter.getData().clear();
                    listAdapter.getData().addAll(beans);
                    listAdapter.notifyDataSetChanged();
                }else{//内容为空，加载原数据
                    getDataList(owner);
                }
                return true;
            }
        });
    }

    public void getGoodsList(int page,LifecycleOwner owner,FragmentHomeBinding binding){

        getGoodsByPage(binding,owner);
        getDataList(owner);



    }

    public void getDataList(LifecycleOwner owner){
        goodList = typeRepos.getGoodList(page, 10);
        goodList.observe(owner, new Observer<GoodsEntity>() {
            @Override
            public void onChanged(GoodsEntity goodsEntity) {
                listAdapter.getData().addAll(goodsEntity.getData());
                listAdapter.notifyDataSetChanged();

                for (GoodsEntity.DataBean good:goodsEntity.getData()
                ) {
                    //查询本条数据在room中不为空，说明存储过

                    typeRepos.getGoodsByid(good.getId(), new Consumer() {
                        @Override
                        public void accept(Object o) throws Exception {
                            List<Goods> list=(List<Goods>) o;
                            if(list!=null&&list.size()!=0){
                                //Log.i("===", good.getGoods_desc() + "已存储过");
                            }else {
                                Goods goods = new Goods(good.getId(),good.getCategory_id(), good.getGoods_desc(), good.getGoods_default_price(), good.getGoods_default_icon());
                                typeRepos.insert(goods, new Action() {
                                    @Override
                                    public void run() throws Exception {
                                        //Log.i("===", good.getGoods_desc() + "存入成功");
                                    }
                                });
                            }
                        }
                    });

                }

            }
        });
    }

    public void getGoodsByPage(FragmentHomeBinding binding,LifecycleOwner owner){
        binding.smart.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getDataList(owner);
                binding.smart.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page=1;
                listAdapter.getData().clear();
                getDataList(owner);
                binding.smart.finishRefresh();
            }
        });
    }

    public void getGoodsBYNoNet(LifecycleOwner owne,FragmentHomeBinding binding){
        //查询room
        typeRepos.select(new Consumer() {
            @Override
            public void accept(Object o) throws Exception {
                List<Goods> list=(List<Goods>)o;
                //List<Goods> list = liveData.getValue();

                GoodsEntity.DataBean bean ;
                listAdapter.getData().clear();
                ArrayList<GoodsEntity.DataBean> dataBeans = new ArrayList<>();
                for (Goods good:list
                ) {
                    //Log.i("===",good.toString());
                    bean = new GoodsEntity.DataBean();
                    bean.setCategory_id(good.getTid());
                    bean.setId(good.getId());
                    bean.setGoods_desc(good.getTitle());
                    bean.setGoods_default_icon(good.getIcon());
                    bean.setGoods_default_price(good.getPrice());
                    dataBeans.add(bean);
                }
                listAdapter.getData().addAll(dataBeans);
                listAdapter.notifyDataSetChanged();
            }
        });

    }
}
